package service

import (
	"context"
	"errors"
	"fmt"
	log "github.com/go-kit/kit/log"
	"mytest/kitcli/user/pkg/transport/grpc/pb"
)

// Middleware describes a service middleware.
type Middleware func(UserService) UserService

type loggingMiddleware struct {
	logger log.Logger
	next   UserService
}

// LoggingMiddleware takes a logger as a dependency
// and returns a UserService Middleware.
func LoggingMiddleware(logger log.Logger) Middleware {
	return func(next UserService) UserService {
		defer func() {
			if err := recover(); err != nil {
				fmt.Println("我回复了")
			}
		}()
		return &loggingMiddleware{logger, next}
	}

}

func (l loggingMiddleware) GetUserList(ctx context.Context, request *pb.GetUserListRequest) (result interface{}, err error) {
	defer func() {
		if e := recover(); e != nil {
			str, ok := e.(string)
			if ok {
				err = errors.New(str)
			} else {
				err = errors.New("panic")
			}
		}
		l.logger.Log("method", "GetTrafficBanList", "request", request, "result", result, "err", err)
	}()
	return l.next.GetUserList(ctx, request)
}
func (l loggingMiddleware) AddUser(ctx context.Context, request *pb.AddUserRequest) (result interface{}, err error) {
	defer func() {
		l.logger.Log("method", "AddUser", "request", request, "result", result, "err", err)
	}()
	return l.next.AddUser(ctx, request)
}
func (l loggingMiddleware) UpdateUser(ctx context.Context, request *pb.UpdateUserRequest) (result interface{}, err error) {
	defer func() {
		l.logger.Log("method", "UpdateUser", "request", request, "result", result, "err", err)
	}()
	return l.next.UpdateUser(ctx, request)
}
func (l loggingMiddleware) DeleteUser(ctx context.Context, request *pb.DeleteUserRequest) (result interface{}, err error) {
	defer func() {
		l.logger.Log("method", "DeleteUser", "request", request, "result", result, "err", err)
	}()
	return l.next.DeleteUser(ctx, request)
}
func (l loggingMiddleware) FindUser(ctx context.Context, request *pb.FindUserRequest) (result interface{}, err error) {
	defer func() {
		l.logger.Log("method", "FindUser", "request", request, "result", result, "err", err)
	}()
	return l.next.FindUser(ctx, request)
}
